﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
public static class SkillConfigHelper
{
    public static List<SkillItem> ReadConfig(string path)
    {
        FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
        StringBuilder sb = new StringBuilder();

        byte[] buffer = new byte[1024 * 32];  //   32字节

        while (true)
        {
            int r = fsRead.Read(buffer, 0, buffer.Length);

            sb.Append(Encoding.UTF8.GetString(buffer));

            if (r < buffer.Length)
                break;
        }

        fsRead.Close();
        fsRead.Dispose();

        return AnalyzeText(sb.ToString());
    }


    private static List<SkillItem> AnalyzeText(string text)
    {
        string[] lines = text.Split('\n');

        //  忽略标题行
        if (lines.Length < 2)
            return null;
        List<SkillItem> result = new List<SkillItem>();

        string line;
        for (int i = 1; i < lines.Length; i++)
        {
            line = lines[i];
            string[] items = line.Split(',', '，');

            if (items.Length < 8)       //  此时如果不完整的话
                continue;

            SkillItem skill = AnalyzeLine(items);

            //  分析结束 添加到列表中
            result.Add(skill);
        }


        return result;
    }

    private static SkillItem AnalyzeLine(string[] items)
    {
        SkillItem skill = new SkillItem(null);
        //  动作名称
        skill.name = items[0];
        //  触发类型
        skill.invokeType = (SkillInvokeType)Enum.Parse(typeof(SkillInvokeType), items[1]);

        //  按键列表
        string[] keys = items[2].Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var key in keys)
        {
            if (Enum.IsDefined(typeof(KeyCode), key))
                skill.hotKeys.Add((KeyCode)Enum.Parse(typeof(KeyCode), key));
        }
        //  伤害
        int.TryParse(items[3], out skill.damage);
        //  参数1
        int.TryParse(items[4], out skill.param1);
        //  硬直时间
        float.TryParse(items[5], out skill.frozenTime);
        //  切换动作时间
        float.TryParse(items[6], out skill.changeTime);
        //  是否是连招最后一个？
        skill.isLastComboItem = items[7].Trim() == "是" || items[7].Trim().ToLower() == "true";

        return skill;
    }


}
